<template>
	<div class="game-container report-container editRolePage-container">
		<div class="roleEdit-content">
			<div class="form-header">
				<span>
					{{ isEdit ? $t('system.edit') : $t('system.create') }}
				</span>
				<span>
					<el-button type="success" size="medium" @click="back">
						{{ $t('common.back') }}
					</el-button>
				</span>
			</div>
			<div class="content-part2">
				<p class="part-title">
					{{ $t('system.role_manage.base_info') }}
				</p>
				<el-form
					ref="form"
					:model="queryData"
					:rules="rules"
					label-width="100px"
					class="picture-form"
					:validate-on-rule-change="false"
				>
					<el-form-item
						:label="`${$t('common.choose_merchant')}:`"
						prop="merchantId"
					>
						<el-select
							v-model="queryData.merchantId"
							size="medium"
							:disabled="isEdit"
							:filterable="true"
							@change="handleMerchantChange"
							style="width: 365px"
						>
							<el-option
								v-if="isZk"
								:label="`${$t('system.all')}`"
								value="0"
							></el-option>
							<el-option
								v-for="item in merchantList"
								:key="item.id"
								:label="item.merchantName"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						:label="`${$t('system.role_name')}:`"
						prop="roleName"
					>
						<el-input
							v-model="queryData.roleName"
							v-symbols
							size="medium"
							maxlength="20"
							:placeholder="$t('common.please_enter')"
							clearable
							show-word-limit
							:disabled="updateStatus"
							style="width: 365px"
						></el-input>
					</el-form-item>
					<el-form-item
						:label="`${$t('system.role_manage.description')}:`"
						prop="remark"
					>
						<el-input
							v-model.trim="queryData.remark"
							size="medium"
							type="textarea"
							:placeholder="
								$t('system.role_manage.input_content')
							"
							clearable
							:disabled="updateStatus"
							maxlength="50"
							show-word-limit
							style="width: 365px"
							@input="handleInput"
						></el-input>
					</el-form-item>
				</el-form>
			</div>
			<div class="content-part3">
				<p class="part-title">
					{{ $t('system.role_manage.permission') }}
				</p>
				<div class="role-container">
					<div class="tree-content">
						<el-tree
							ref="tree"
							:data="rolePermissions"
							:default-checked-keys="checkedKeys"
							node-key="id"
							show-checkbox
							:props="defaultProps"
							:check-on-click-node="true"
							@check="handleCheck"
							@check-change="handleCheckChange"
						></el-tree>
					</div>
				</div>
				<el-checkbox
					v-model="chooseAll"
					class="chooseAll"
					:indeterminate="isIndeterminate"
					@change="handleAllChoose"
				>
					{{ $t('system.role_manage.select_all') }}
				</el-checkbox>
			</div>
			<div class="save-container">
				<div class="save-btn" @click.prevent="save">
					<i v-show="loading" class="el-icon-loading"></i>
					{{ $t('common.save') }}
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import list from '@/mixins/list'
import { isHaveEmoji, notSpecial2 } from '@/utils/validate'
import i18n from '@/locales'
// import { NO_SPECIAL_CHAR } from '@/utils/pattern'
export default {
	name: 'EditPage',
	mixins: [list],
	props: {
		editData: {
			type: Object,
			default: () => {}
		},
		isEdit: {
			type: Boolean,
			required: true
		}
	},
	data() {
		this.save = this.throttle(this.save, 2000)
		return {
			loading: false,
			queryData: {
				merchantId: '0',
				roleName: undefined,
				remark: undefined,
				id: undefined
			},
			chooseAll: false,
			dataList: [],
			rolePermissions: [],
			permissions: [],
			checkedKeys: [],
			chooseIds: [],
			chooseId: [],
			allChooseLen: 0,
			isIndeterminate: false,
			updateStatus: false
		}
	},
	computed: {
		currentUserType() {
			return this.$store.getters.userInfo.userType
		},
		merchantList() {
			return this.$store.getters.merchantList || []
		},
		showMerchantSelect() {
			return !(this.isZk && this.isEdit)
		},
		isZk() {
			return this.$store.getters.isZk
		},
		currentMerchantId() {
			return this.$store.getters.merchantInfo.id || '0'
		},
		rules() {
			const testPicName = (rule, value, callback) => {
				const isSpecial = !notSpecial2(String(value))
				const isRmoji = isHaveEmoji(String(value))
				if (isSpecial) {
					callback(
						new Error(
							this.$t('system.role_manage.not_support_space')
						)
					)
				} else if (isRmoji) {
					callback(
						new Error(
							this.$t('system.role_manage.not_support_face')
						)
					)
				} else if (!value) {
					callback(
						new Error(this.$t('system.role_manage.input_name'))
					)
				} else {
					callback()
				}
			}
			const roleName = [
				{
					required: true,
					validator: testPicName,
					trigger: 'blur'
				}
			]
			const merchantId = [
				{
					required: true,
					message: this.$t('common.components.select_merchant'),
					trigger: 'change'
				}
			]
			const remark = [
				{
					required: true,
					message: this.$t(
						'system.role_manage.please_input_description'
					),
					trigger: 'blur'
				},
				{
					min: 2,
					max: 50,
					message: this.$t('system.role_manage.limit'),
					trigger: 'blur'
				}
			]
			return {
				roleName,
				remark,
				merchantId
			}
		},
		defaultProps() {
			return {
				label: (data) => {
					return data.permissionName
				},
				children: 'children'
			}
		}
	},
	watch: {
		editData: {
			handler(newData, oldData) {
				const _newData = newData && JSON.parse(JSON.stringify(newData))
				const _oldData = oldData && JSON.parse(JSON.stringify(oldData))
				if (_newData && _newData !== _oldData) {
					this.updateStatus = true
					const { id, roleName, remark, merchantId } = newData
					this.queryData = {
						roleName,
						merchantId: String(merchantId),
						remark,
						id
					}
				} else {
					this.updateStatus = false
					this.queryData = {
						roleName: undefined,
						merchantId: String(this.currentMerchantId),
						remark: undefined,
						id: undefined
					}
					this.chooseIds = []
					this.$nextTick(() => {
						this.$refs.tree && this.$refs.tree.setCheckedKeys([])
					})
				}
			},
			deep: true,
			immediate: true
		},
		chooseIds: {
			handler(newData, oldData) {
				const _newData = newData && JSON.parse(JSON.stringify(newData))
				const _oldData = oldData && JSON.parse(JSON.stringify(oldData))
				if (_newData && _newData !== _oldData) {
					this.$nextTick(() => {
						newData.forEach((item) => {
							const node = this.$refs.tree.getNode(item)
							if (node.isLeaf) {
								this.$refs.tree.setChecked(node, true)
							}
						})
					})
				}
			},
			deep: true,
			immediate: true
		}
	},
	created() {
		this.getRoleList()
	},
	methods: {
		handleInput(val) {
			// this.queryData.remark = val.replace(NO_SPECIAL_CHAR, '')
		},
		handleMerchantChange() {
			this.getRoleList()
		},
		back() {
			this.$emit('back')
		},
		async getRoleList() {
			this.loading = true
			const res = await this.$api
				.getRolePermissionsAPI({
					userType: this.currentUserType,
					merchantId: this.queryData.merchantId,
					roleId: this.editData ? this.editData.id : undefined
				})
				.catch(() => {
					this.loading = false
				})

			let showPermissionArr = []
			if (Array.isArray(res?.data)) {
				// showPermissionArr = res.data
				const hideParentPermissionIds = []
				// 获取二级菜单隐藏id
				res.data.forEach((item) => {
					if (item?.visible === 0) {
						hideParentPermissionIds.push(item.id)
					}
				})
				// 获取三级菜单隐藏id
				res.data.forEach((item) => {
					if (hideParentPermissionIds.indexOf(item.parentId) > -1) {
						hideParentPermissionIds.push(item.id)
					}
				})
				showPermissionArr = res.data.filter(
					(item) =>
						hideParentPermissionIds.indexOf(item.parentId) === -1 &&
						item?.visible !== 0
				)
			}
			this.permissions = JSON.parse(JSON.stringify(showPermissionArr))
			this.allChooseLen = showPermissionArr.length
			this.rolePermissions = []
			this.filterData(showPermissionArr)

			this.loading = false
		},
		filterData(data) {
			const _data = [...data]
			_data.forEach((ele, i) => {
				const index = data.findIndex((val) => val.id === ele.parentId)
				if (index < 0) {
					this.rolePermissions.push({
						id: ele.id,
						label: ele.permissionName.includes('/')
							? ele.permissionName
									.split('/')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('/')
							: ele.permissionName
									.split('-')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('-'),
						children: [],
						...ele,
						permissionName: ele.permissionName.includes('/')
							? ele.permissionName
									.split('/')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('/')
							: ele.permissionName
									.split('-')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('-')
					})
				}
				if (ele.isExist === '1') {
					this.chooseIds.push(ele.id)
				}
			})
			this.generateData(_data, this.rolePermissions)
		},
		generateData(data, tree) {
			const data_s = [...data]
			const pickIndex = []
			const leftData = []
			data_s.forEach((ele) => {
				const index = tree.findIndex((val) => val.id === ele.parentId)
				if (index > -1) {
					tree[index].children.push({
						id: ele.id,
						label: ele.permissionName.includes('/')
							? ele.permissionName
									.split('/')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('/')
							: ele.permissionName
									.split('-')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('-'),
						children: [],
						...ele,
						permissionName: ele.permissionName.includes('/')
							? ele.permissionName
									.split('/')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('/')
							: ele.permissionName
									.split('-')
									.map((name) =>
										i18n.te(name) ? i18n.t(name) : name
									)
									.join('-')
					})
					if (ele.type === '1') {
						!pickIndex.includes(index) &&
							tree[index].children.unshift({
								id: ele.parentId,
								label: this.$t('system.role_manage.display'),
								permissionName: this.$t(
									'system.role_manage.display'
								),
								children: null,
								type: '1'
							})
						!pickIndex.includes(index) &&
							this.chooseId.push('look' + ele.parentId)
					}
					!pickIndex.includes(index) && pickIndex.push(index)
				} else {
					leftData.push(ele)
				}
			})
			if (pickIndex.length > 0) {
				pickIndex.forEach((ele) => {
					this.generateData(leftData, tree[ele].children)
				})
			}
		},
		handleCheck(checkedNodes, checkedKeys) {
			this.chooseIds = checkedKeys.checkedKeys.concat(
				checkedKeys.halfCheckedKeys
			)
			!!this.chooseIds.length && this.chooseIds.length < this.allChooseLen
				? (this.chooseAll = false) && (this.isIndeterminate = true)
				: this.allChooseLen === this.chooseIds.length
				? (this.chooseAll = true) && (this.isIndeterminate = false)
				: (this.chooseAll = false) && (this.isIndeterminate = false)
		},
		handleAllChoose(val) {
			const ids = this.getAllIds(this.permissions, [])
			this.$nextTick(() => {
				this.$refs.tree.setCheckedKeys(val ? ids : [])
				val ? (this.chooseIds = ids) : (this.chooseIds = [])
			})
			this.isIndeterminate = false
		},
		getAllIds(permissions, arr) {
			permissions.forEach((item) => {
				arr.push(item.id)
				item.children && this.getAllIds(item.children, arr)
			})
			return arr
		},
		handleCheckChange(data) {
			// if (this.$refs.tree) {
			//     const selected = this.$refs.tree.getCheckedKeys()
			//     const ids = this.getAllIds(this.permissions, [])
			//     this.checkAll = selected.length === ids.length
			// }
		},
		save() {
			const params = {
				...this.queryData
			}

			params.permissionId = this.chooseIds.filter(
				(ele) => !(ele + '').includes('look')
			)
			if (
				Array.isArray(params.permissionId) &&
				!params.permissionId.length
			) {
				this.$message.error(
					this.$t('system.role_manage.permission_not_empty')
				)
				return false
			}
			const handle = this.updateStatus
				? this.$api.setUpdateRoleInfoAPI
				: this.$api.setSaveRoleInfoAPI
			this.$refs['form'].validate((valid) => {
				if (valid) {
					this.loading = true
					handle(params)
						.then((res) => {
							this.loading = false
							if (res?.code === 200) {
								this.$message({
									message: `${
										this.updateStatus
											? this.$t(
													'system.role_manage.update_success'
											  )
											: this.$t('common.add_success')
									}`,
									type: 'success'
								})
								this.reset()
								setTimeout(() => {
									this.back()
								}, 1000)
							} else {
								this.$message({
									message:
										res?.msg ||
										this.$t('common.interface_error'),
									type: 'error'
								})
							}
						})
						.catch(() => {
							this.loading = false
						})
				}
			})
		},
		reset() {
			this.$refs['form'].resetFields()
			this.queryData = {
				roleName: undefined,
				merchantId: String(this.currentMerchantId),
				remark: undefined,
				id: undefined
			}
		}
	}
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__header {
	text-align: center;
	color: #909399;
	font-weight: 700;
}
::v-deep .el-button--info {
	background-color: rgba(26, 188, 156, 1);
	color: #fff;
	border-color: rgb(28, 195, 162);
}
::v-deep .el-button--info:hover {
	background-color: #1b9f89;
}
::v-deep .el-button + .el-button {
	margin-left: 0;
	margin-right: 15px;
	margin-bottom: 15px;
}

::v-deep .el-tree-node__content > label.el-checkbox {
	margin-right: 8px;
}

::v-deep .el-tree-node__content {
	height: 36px;
}

.editRolePage-container {
	background-color: #f5f5f5;
	margin: 0;
	min-height: calc(100vh - 105px);
	.roleEdit-content {
		width: 65%;
		margin: 0 auto;
		background-color: #fff;
		position: relative;
		padding-bottom: 30px;
		.form-header {
			height: 55px;
			line-height: 55px;
			width: 100%;
			background-color: rgba(0, 0, 0, 1);
			span:nth-child(1) {
				position: absolute;
				left: 30px;
				top: 0;
				color: rgba(255, 255, 255, 0.847058823529412);
				font-size: 16px;
				font-weight: 700;
			}
			span:nth-child(2) {
				position: absolute;
				right: 30px;
				top: 0;
				color: #999;
				font-weight: 400;
				font-size: 14px;
			}
		}
		.form-header:after {
			content: '.';
			height: 0;
			display: table;
			clear: both;
		}
		.content-part2 {
			width: 100%;
			padding: 25px 35px 20px;
			position: relative;
			margin: 0 auto;
			.picture-form {
				position: relative;
				width: 600px;
				max-width: 100%;
				padding: 35px 35px 0;
				margin: 0 auto;
				overflow: hidden;
			}
		}
		.content-part3 {
			width: 100%;
			padding: 25px 35px 20px;
			margin-top: 45px;
			.role-container {
				padding-left: 15px;
				padding-right: 15px;
				border: 1px solid #eee;
				overflow-y: scroll;
				.tree-content {
					min-height: 400px;
				}
				.btn-style-role {
					width: 120px;
					height: 30px;
					color: #fff;
					border-radius: 0;
				}
				.btn-style-role:nth-child(1) {
					margin-right: 15px;
				}
			}
			// .btn-control {
			// }
			.role-content {
				border: 1px solid #8a90a5;
				margin-top: 10px;
				.name {
					height: 65px;
					line-height: 65px;
					text-align: center;
					color: #666666;
				}
				.el-col:nth-child(2) {
					border-left: 1px solid #8a90a5;
				}
				.btn-group {
					border-top: 1px solid #8a90a5;
					.div-cell {
						line-height: 48px;
						border-bottom: 1px solid #8a90a5;
					}
					.div-cell:last-child {
						border-bottom: 0;
					}
				}
				.btn-group.first {
					margin: 0 auto;
					text-align: center;
					padding-top: 50%;
				}
			}
		}
	}

	.part-title {
		color: rgba(0, 0, 0, 0.847058823529412);
		font-size: 14px;
		font-weight: 650;
		height: 45px;
		line-height: 45px;
		//background-color: #F3F3F3;
	}
	// .cell-group {
	// 	position: absolute;
	// 	display: flex;
	// 	width: 200px;
	// 	height: 1000px;
	// }
	// .child-cell {
	// 	margin: 5px 0 0 20px;
	// }
	.chooseAll {
		width: 100%;
		text-align: center;
		margin-top: 15px;
	}
	.save-container {
		.save-btn {
			text-align: center;
			margin: 0 auto 50px;
			background-color: rgba(26, 188, 156, 1);
			height: 40px;
			line-height: 40px;
			cursor: pointer;
			width: 245px;
			border-radius: 5px;
			font-size: 16px;
			color: #fff;
		}
	}
}
</style>
